<?php

namespace App\Http\Controllers\V1\API;

use App\Http\Controllers\V1\API\BaseController;
use App\Models\V1\Faculty;
use App\Models\V1\InfoNotice;
use App\Models\V1\InfoNoticeProgram;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Symfony\Component\DomCrawler\Crawler;
use Validator;
use Log;
class NoticeDetailsController extends BaseController
{
    /****
     * 获取公告
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getNoticesProgram() {
        // 自定义返回格式
        $result = array(
            'errorCode' => Response::HTTP_NOT_FOUND,
            'errorMsg' => Response::$statusTexts[Response::HTTP_NOT_FOUND],
            'data' => array()
        );
        $programs = $this->getNoticeProgramList();
        if ($programs->isEmpty()) {
            $result['errorCode'] = Response::HTTP_OK;
            $result['errorMsg'] = Response::$statusTexts[Response::HTTP_NO_CONTENT];
        }else {
            // 格式化数据
            $programNotice = array();
            foreach ($programs as $item) {
                $formatStudent = array();
                $formatStudent['programCode'] = $item['code'];
                $formatStudent['programName'] = $item['name'];
                array_push($programNotice, $formatStudent);
            }

            $result['errorCode'] = Response::HTTP_OK;
            $result['errorMsg'] = Response::$statusTexts[Response::HTTP_OK];
            $result['data'] = $programNotice;
        }
        return $this->sendResponse($result, $result['errorCode']);
    }

    /***
     * 根据栏目获取公告
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getNoticesByProgramID(Request $request) {
        $page = $request->get('page');
        //type 不为空，则表示根据栏目id获取栏目下公告  为空：则取最新5条
        $type = $request->get('programCode');
        // 自定义返回格式
        $result = array(
            'errorCode' => Response::HTTP_NOT_FOUND,
            'errorMsg' => Response::$statusTexts[Response::HTTP_NOT_FOUND],
            'data' => array()
        );
        $notice = $this->getNoticeList($page,$type);
        $noticeData = $notice['data'];

        // 格式化数据
        $dataNotice = array(
            'total'=>$notice['total'],
            'currentPage'=>$notice['current_page'],
            'perPage'=>$notice['per_page'],
            'dataList'=>array()
        );

        if (count($noticeData)===0) {
            $result['errorCode'] = Response::HTTP_OK;
            $result['errorMsg'] = Response::$statusTexts[Response::HTTP_NO_CONTENT];
            $result['data'] = $dataNotice;
        } else {
            $dataList = array();
            foreach ($noticeData as $item) {
                $formatNotice = array();
                $formatNotice['noticeCode'] = $item['code'];
                $formatNotice['title'] = $item['title'];
                $formatNotice['type'] = $item['type'];
                $formatNotice['videoCoverPic'] = isset($item['videoCoverPic'])?isset($item['videoCoverPic']):'';;
                $content = json_decode($item['content'], true);
                $imageArr = array();
                if (count($content) > 0) {
                    foreach ($content as $value) {
                        $type = $value['type'];
                        if ($type === 'image') {
                            $url = $value['content'];
                            array_push($imageArr,$url);
                        }
                    }
                }
                 $formatNotice['imgURL'] =$imageArr;
//                $crawler = new Crawler($content);
//                $nodeValues =  $crawler->filterXPath('//body/p/img')->each(function (Crawler $node, $i) {
//                    return $node->attr('src');
//                });
//                $c = $crawler->filterXPath('//body')->filter('img');
//                if ($c->count()>0) {
//                    $imgURL = $c->attr('src');
//                }else {
//                    $imgURL = '';
//                }
//                if (!in_array($imgURL,$nodeValues)) {
//                    array_push($nodeValues,$imgURL);
//                }
//                $formatNotice['imgURL'] =$nodeValues;
                array_push($dataList, $formatNotice);
            }
            $dataNotice['dataList'] = $dataList;
            $result['errorCode'] = Response::HTTP_OK;
            $result['errorMsg'] = Response::$statusTexts[Response::HTTP_OK];
            $result['data'] = $dataNotice;
        }
        return $this->sendResponse($result, $result['errorCode']);
    }


    /***
     * 获取公告详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getNoticeDetailByID(Request $request) {
        $result = array(
            'errorCode' => Response::HTTP_NOT_FOUND,
            'errorMsg' => Response::$statusTexts[Response::HTTP_NOT_FOUND],
            'data' => array()
        );
        $error = $this->validateNotice($request, $result);
        if (!empty($error) || isset($error)) {
            $result = $error;
            return $this->sendResponse($result, $result['errorCode']);
        }

        $notice_code = $request->get('noticeCode');
        $info_notice = InfoNotice::where('code',$notice_code)->first();
        if (!empty($info_notice) || isset($info_notice)) {
            $formatNotice = array();
            $formatNotice['noticeCode'] = $info_notice['code'];
            $formatNotice['title'] = $info_notice['title'];
            $formatNotice['programCode'] = $info_notice['program_code'];
            $formatNotice['programName'] = InfonoticeProgram::where('code',$info_notice['program_code'])->first()->name;
            $formatNotice['type'] = $info_notice['type'];
            $formatNotice['videoCoverPic'] = isset($info_notice['videoCoverPic'])?isset($info_notice['videoCoverPic']):'';
            $content = json_decode($info_notice['content'], true);
            $formatNotice['content'] = $content;
            $objPublisher = $this->getFacultyByCode($info_notice['publisher_code']);
            $formatNotice['publisherCode'] = $info_notice['publisher_code'];
            $formatNotice['publisherName'] = empty($objPublisher) ? "未知" : $objPublisher['name'];;
            $result['data'] = $formatNotice;
            $result['errorCode'] = Response::HTTP_OK;
            $result['errorMsg'] = Response::$statusTexts[Response::HTTP_OK];
        }else {
            $result['errorCode'] = Response::HTTP_OK;
            $result['errorMsg'] = Response::$statusTexts[Response::HTTP_NO_CONTENT];
        }
        return $this->sendResponse($result, $result['errorCode']);
    }


    /***
     * 致新生的信
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getStudentMessage(Request $request) {
        $info_notice = InfoNotice::where(['program_code'=>'100','isShow'=>true])->orderBy('updated_at','desc')->first();
        if (!empty($info_notice) || isset($info_notice)) {
            $formatNotice = array();
            $content = json_decode($info_notice['content'], true);
            $formatNotice['content'] = $content;
            $objPublisher = $this->getFacultyByCode($info_notice['publisher_code']);
            $formatNotice['publisherCode'] = $info_notice['publisher_code'];
            $formatNotice['publisherName'] = empty($objPublisher) ? "未知" : $objPublisher['name'];;
            $result['data'] = $formatNotice;
            $result['errorCode'] = Response::HTTP_OK;
            $result['errorMsg'] = Response::$statusTexts[Response::HTTP_OK];
        }else {
            $result['errorCode'] = Response::HTTP_OK;
            $result['errorMsg'] = Response::$statusTexts[Response::HTTP_NO_CONTENT];
        }
        return $this->sendResponse($result, $result['errorCode']);
    }

    /***
     * 学校概况
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getSchoolSituation(Request $request) {
        $info_notice = InfoNotice::where(['program_code'=>'200','isShow'=>true])->orderBy('updated_at','desc')->first();
        if (!empty($info_notice) || isset($info_notice)) {
            $formatNotice = array();
            $content = json_decode($info_notice['content'], true);
            $formatNotice['content'] = $content;
            $objPublisher = $this->getFacultyByCode($info_notice['publisher_code']);
            $formatNotice['publisherCode'] = $info_notice['publisher_code'];
            $formatNotice['publisherName'] = empty($objPublisher) ? "未知" : $objPublisher['name'];;
            $result['data'] = $formatNotice;
            $result['errorCode'] = Response::HTTP_OK;
            $result['errorMsg'] = Response::$statusTexts[Response::HTTP_OK];
        }else {
            $result['errorCode'] = Response::HTTP_OK;
            $result['errorMsg'] = Response::$statusTexts[Response::HTTP_NO_CONTENT];
        }
        return $this->sendResponse($result, $result['errorCode']);
    }

    ///////////////////////////////////////////////////////////////////
    /// 获取数据功能函数
    ///////////////////////////////////////////////////////////////////

    private function getNoticeList($page = 1,$type, $rows = 10)
    {
        if (!isset($type) || empty($type)) {
            $rows = 5;
            $data = InfoNotice::where('isShow',1)
                ->orderBy('created_at', 'desc')
                ->paginate($rows, ['*'], 'page', $page)->toJson();
        }else {
            $data = InfoNotice::where('program_code',$type)
                ->where('isShow',1)
                ->orderBy('created_at', 'desc')
                ->paginate($rows, ['*'], 'page', $page)->toJson();
        }
        return json_decode($data,true);
    }

    /****
     * 获取所有栏目
     * @return \Illuminate\Support\Collection
     */
    private function getNoticeProgramList()
    {
        $data = InfoNoticeProgram::orderBy('id','asc')->get();
        return $data;
    }

    /**
     * 根据教职工代码获取对应教职工信息
     *
     * @param $code
     * @return \Illuminate\Database\Eloquent\Model|null|static
     */
    private function getFacultyByCode($code)
    {
        $term = Faculty::where('code', $code)->first();
        return $term;
    }

    /***
     * 验证参数
     * @param Request $request
     * @return mixed
     */
    public function validateNotice(Request $request)
    {
        //校验规则
        $rules = array();
        $rules['noticeCode'] = 'required';

        //错误提示信息
        $messages = array();
        $messages['noticeCode.required'] = '公告ID不能为空';

        $validator = Validator::make($request->all(),$rules,$messages);  //第一个参数是提交的数据，第二个是校对规则，第三个是错误信息
        $errors = $validator->errors()->all(); //这是捕获到的所有参数验证的错误信息
        if(!empty($errors)) {
            $first_errors = $errors[0];
            $result['errorCode'] = Response::HTTP_BAD_REQUEST;
            $result['errorMsg'] = $first_errors;
            return $result;
        }
    }

//    /**
//     * 转化html->json
//     */
//    private function getContent($content) {
//        $content = array();
//        for($i=0; $i<count($content);$i++) {
//            $item='';
//        }
//
//    }
}
